package com.gitee.linmt.factory;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * 读取 yaml.
 *
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    
    @NonNull
    @Override
    public PropertySource<?> createPropertySource(@Nullable final String name, @NonNull final EncodedResource resource)
            throws IOException {
        final Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        final String sourceName = name != null ? name : resource.getResource().getFilename();
        assert sourceName != null;
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }
    
    private Properties loadYamlIntoProperties(final EncodedResource resource) throws FileNotFoundException {
        try {
            final YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (final IllegalStateException e) {
            // for ignoreResourceNotFound
            final Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException) {
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }
}
